﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.Core.Support;
using Microsoft.SharePoint;
using MS.InformationManagement.Support;
using MS.InformationManagement.Support.Exceptions;
using MS.InformationManagement.DAL.DocumentCenter;
using MS.InformationManagement.Support.Constants;
using Microsoft.SharePoint.Taxonomy;

namespace MS.InformationManagement.Core.Support
{
    public class SendEmailCommand : IBaseCommand
    {
        private int _DocID;
        private SPUser _From;
        private SPUser _To;
        private string _LibraryId;
        private SPWeb _Web;
        private SPListItem _Document;
        private string _DocType;
        private bool _IsReassignement;

        public SendEmailCommand(string To, SPListItem Document, int DocID, string LibraryID, string DocType, bool IsReassignement, SPWeb Web)
        {
            //_FromLoginName = FromLoginName;
            _To = PeopleHelper.GetUserByLoginName(To).User;
            _Web = Web;
            _Document = Document;
            _DocID = DocID;
            _DocType = DocType;
            _LibraryId = LibraryID;
            _IsReassignement = IsReassignement;
        }

        public SendEmailCommand(SPListItem Document, int DocID, string LibraryID, string DocType, bool IsReassignement, SPWeb Web)
        {
            //_FromLoginName = FromLoginName;
            //_ToLoginName = ToLoginName;
            _Web = Web;
            _Document = Document;
            _DocID = DocID;
            _DocType = DocType;
            _LibraryId = LibraryID;
            _IsReassignement = IsReassignement;
        }

        public SendEmailCommand(SPUser From, SPUser To, SPListItem Document, int DocID, string LibraryID, string DocType, bool IsReassignement, SPWeb Web)
        {
            _From = From;
            _To = To;
            _Web = Web;
            _Document = Document;
            _DocID = DocID;
            _DocType = DocType;
            _LibraryId = LibraryID;
            _IsReassignement = IsReassignement;
        }

        public void Execute()
        {
            try
            {
                switch (_DocType)
                {
                    case GlobalConstants.CTTN_RADICADO_EMPRESA:
                    case GlobalConstants.CTTN_RADICADO_PERSONA:
                        if (_IsReassignement)
                        {
                            if (_Document[CustomSiteColumns.FIELD_DOCUMENT_MAXRESPONSEDATE] != null)
                            {
                                SendClassifiedReassignedDocNotification();
                            }
                            else
                            {
                                SendUnclassifiedReassignedDocNotification();
                            }
                        }
                        else
                        {
                            if (_Document[CustomSiteColumns.FIELD_DOCUMENT_MAXRESPONSEDATE] != null)
                            {
                                SendClassifiedIncommingDocNotification();
                            }
                            else
                            {
                                SendUnclassifiedIncommingDocNotification();
                            }
                        }
                        break;
                    case GlobalConstants.CTTN_INFORMATION:
                        SendInformDocNotification();
                        break;
                }
            }
            catch (Exception ex)
            {
                throw new NotificationException("La operación que esta intentando realizar fue exitosa; sin embargo las notificaciones asociadas a dicha operación no pudieron ser enviadas", ex);
            }
        }

        public void Undo()
        {
            //throw new NotImplementedException();
        }

        private void SendUnclassifiedIncommingDocNotification()
        {
            SPUser targetUser = _To == null ? new SPFieldUserValue(_Document.Web, _Document[CustomSiteColumns.FIELD_DOCSET_DESTINATARIO].ToString()).User : _To;
            string subject = ConfigurationHelper.GetInstance().ConfigItems[GlobalConstants.NOTIFICACION_ASUNTO_ENTRADA_SIN_TIPIFICAR];

            Dictionary<string, string> tokenizedValues = new Dictionary<string, string>();
            tokenizedValues.Add("[[USERFULLNAME]]", targetUser.Name);
            tokenizedValues.Add("[[DOCNUMBER]]", _Document[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID].ToString());
            tokenizedValues.Add("[[FROM]]", _Document[CustomSiteColumns.FIELD_DOCSET_SENDERRECEPT].ToString());
            tokenizedValues.Add("[[DOCSUBJECT]]", _Document[CustomSiteColumns.FIELD_DOCUMENT_ASUNTO].ToString());
            tokenizedValues.Add("[[DOCURL]]", string.Format("{0}/_layouts/listform.aspx?PageType=6&ListId={1}&ID={2}", _Web.Url, "{" + _LibraryId + "}", _DocID));

            if (!EmailHelper.SendEmail(SPContext.Current.Web.CurrentUser.LoginName
                , targetUser.LoginName, subject, GlobalConstants.NOTIFICACION_TEMPLATE_ENTRADA_SIN_TIPIFICAR
                , tokenizedValues, _Web))
            {
                throw new Exception("No se pudo enviar la notificación");
            }

        }

        private void SendClassifiedIncommingDocNotification()
        {
            SPUser targetUser = _To == null ? new SPFieldUserValue(_Document.Web, _Document[CustomSiteColumns.FIELD_DOCSET_DESTINATARIO].ToString()).User : _To;
            string subject = ConfigurationHelper.GetInstance().ConfigItems[GlobalConstants.NOTIFICACION_ASUNTO_ENTRADA_TIPIFICADO];

            Dictionary<string, string> tokenizedValues = new Dictionary<string, string>();
            tokenizedValues.Add("[[USERFULLNAME]]", targetUser.Name);
            tokenizedValues.Add("[[DOCNUMBER]]", _Document[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID].ToString());
            tokenizedValues.Add("[[FROM]]", _Document[CustomSiteColumns.FIELD_DOCSET_SENDERRECEPT].ToString());
            tokenizedValues.Add("[[DOCSUBJECT]]", _Document[CustomSiteColumns.FIELD_DOCUMENT_ASUNTO].ToString());
            tokenizedValues.Add("[[DOCURL]]", string.Format("{0}/_layouts/listform.aspx?PageType=6&ListId={1}&ID={2}", _Web.Url, "{" + _LibraryId + "}", _DocID));
            tokenizedValues.Add("[[DATE]]", Convert.ToDateTime(_Document[CustomSiteColumns.FIELD_DOCUMENT_MAXRESPONSEDATE]).ToString("MMMM dd, yyyy"));

            if (!EmailHelper.SendEmail(SPContext.Current.Web.CurrentUser.LoginName
                , targetUser.LoginName, subject, GlobalConstants.NOTIFICACION_TEMPLATE_ENTRADA_TIPIFICADO
                , tokenizedValues, _Web))
            {
                throw new Exception("No se pudo enviar la notificación");
            }
        }

        private void SendUnclassifiedReassignedDocNotification()
        {
            SPUser targetUser = _To == null ? new SPFieldUserValue(_Document.Web, _Document[CustomSiteColumns.FIELD_DOCSET_DESTINATARIO].ToString()).User : _To;
            string subject = ConfigurationHelper.GetInstance().ConfigItems[GlobalConstants.NOTIFICACION_ASUNTO_REASIGNACION_SIN_TIPIFICAR];
            string currentUserDependency = PeopleHelper.GetPropertyCurrentUserProfile(GlobalConstants.UP_DEPARTMENT);

            Dictionary<string, string> tokenizedValues = new Dictionary<string, string>();
            tokenizedValues.Add("[[USERFULLNAME]]", targetUser.Name);
            tokenizedValues.Add("[[DOCNUMBER]]", _Document[CustomSiteColumns.FIELD_DOCSET_ID_RADICADO].ToString());
            tokenizedValues.Add("[[FROM]]", _Document[CustomSiteColumns.FIELD_DOCSET_SENDERRECEPT].ToString());
            tokenizedValues.Add("[[DOCSUBJECT]]", _Document[CustomSiteColumns.FIELD_DOCUMENT_ASUNTO].ToString());
            tokenizedValues.Add("[[DOCURL]]", string.Format("{0}/_layouts/listform.aspx?PageType=6&ListId={1}&ID={2}", _Web.Url, "{" + _LibraryId + "}", _DocID));
            tokenizedValues.Add("[[REASIGNEDBYSECTION]]", currentUserDependency);
            tokenizedValues.Add("[[REASIGNEDBY]]", SPContext.Current.Web.CurrentUser.Name);

            if (!EmailHelper.SendEmail(SPContext.Current.Web.CurrentUser.LoginName
                , targetUser.LoginName, subject, GlobalConstants.NOTIFICACION_TEMPLATE_REASIGNACION_SIN_TIPIFICAR
                , tokenizedValues, _Web))
            {
                throw new Exception("No se pudo enviar la notificación");
            }
        }

        private void SendClassifiedReassignedDocNotification()
        {
            SPUser targetUser = _To == null ? new SPFieldUserValue(_Document.Web, _Document[CustomSiteColumns.FIELD_DOCSET_DESTINATARIO].ToString()).User : _To;
            string subject = ConfigurationHelper.GetInstance().ConfigItems[GlobalConstants.NOTIFICACION_ASUNTO_REASIGNACION_TIPIFICADO];
            string currentUserDependency = PeopleHelper.GetPropertyCurrentUserProfile(GlobalConstants.UP_DEPARTMENT);

            Dictionary<string, string> tokenizedValues = new Dictionary<string, string>();
            tokenizedValues.Add("[[USERFULLNAME]]", targetUser.Name);
            tokenizedValues.Add("[[DOCNUMBER]]", _Document[CustomSiteColumns.FIELD_DOCSET_ID_RADICADO].ToString());
            tokenizedValues.Add("[[FROM]]", _Document[CustomSiteColumns.FIELD_DOCSET_SENDERRECEPT].ToString());
            tokenizedValues.Add("[[DOCSUBJECT]]", _Document[CustomSiteColumns.FIELD_DOCUMENT_ASUNTO].ToString());
            tokenizedValues.Add("[[DOCURL]]", string.Format("{0}/_layouts/listform.aspx?PageType=6&ListId={1}&ID={2}", _Web.Url, "{" + _LibraryId + "}", _DocID)); ;
            tokenizedValues.Add("[[REASIGNEDBYSECTION]]", currentUserDependency);
            tokenizedValues.Add("[[REASIGNEDBY]]", SPContext.Current.Web.CurrentUser.Name);
            tokenizedValues.Add("[[DATE]]", Convert.ToDateTime(_Document[CustomSiteColumns.FIELD_DOCUMENT_MAXRESPONSEDATE]).ToString("MMMM dd, yyyy"));

            if (!EmailHelper.SendEmail(SPContext.Current.Web.CurrentUser.LoginName
                , targetUser.LoginName, subject, GlobalConstants.NOTIFICACION_TEMPLATE_REASIGNACION_TIPIFICADO
                , tokenizedValues, _Web))
            {
                throw new Exception("No se pudo enviar la notificación");
            }
        }

        private void SendInformDocNotification()
        {
            string subject = ConfigurationHelper.GetInstance().ConfigItems[GlobalConstants.NOTIFICACION_ASUNTO_INFORMAR];
            string currentUserDependency = PeopleHelper.GetPropertyCurrentUserProfile(GlobalConstants.UP_DEPARTMENT);
            subject = string.Format(subject, (_Document[CustomSiteColumns.FIELD_DOCSET_KIND] as TaxonomyFieldValue).Label);

            Dictionary<string, string> tokenizedValues = new Dictionary<string, string>();
            tokenizedValues.Add("[[USERFULLNAME]]", _To.Name);
            tokenizedValues.Add("[[DOCNUMBER]]", _Document[CustomSiteColumns.FIELD_DOCSET_ID_RADICADO].ToString());
            tokenizedValues.Add("[[FROM]]", _Document[CustomSiteColumns.FIELD_DOCSET_SENDERRECEPT].ToString());
            tokenizedValues.Add("[[DOCSUBJECT]]", _Document[CustomSiteColumns.FIELD_DOCUMENT_ASUNTO].ToString());
            tokenizedValues.Add("[[DOCURL]]", string.Format("{0}/_layouts/listform.aspx?PageType=6&ListId={1}&ID={2}", _Web.Url, "{" + _LibraryId + "}", _DocID));
            tokenizedValues.Add("[[REASIGNEDBYSECTION]]", currentUserDependency);
            tokenizedValues.Add("[[REASIGNEDBY]]", SPContext.Current.Web.CurrentUser.Name);

            if (!EmailHelper.SendEmail(SPContext.Current.Web.CurrentUser.LoginName
                , _To.LoginName, subject, GlobalConstants.NOTIFICACION_TEMPLATE_INFORMAR
                , tokenizedValues, _Web))
            {
                throw new Exception("No se pudo enviar la notificación");
            }
        }
    }
}
